import * as types from '../mutation-types';
import {fetch} from 'utils/api.js';
import Tools from 'utils/tools.js';

const state = {
  show: false,
  model: false,
  type: 'float-box-alert',
  content: null,
  promise: {
    resolve: ()=>{},
    reject: ()=>{}
  }
};

const mutations = {
  // 显示浮层
  [types.SHOW_FLOAT_BOX](state) {
    state.show = true;
  },
  // 隐藏浮层
  [types.HIDE_FLOAT_BOX](state) {
    state.show = false;
  },
  // 设置浮层
  [types.SET_FLOAT_BOX_CONFIG](state, config) {
    state.model = config.model;
    state.type = config.type;
    state.content = config.content;
  },
  // 设置promise回调
  [types.SET_FLOAT_BOX_PROMISE](state, promise) {
    state.promise = promise
  }
};


const actions = {
  alert({dispatch}, content){
    dispatch('setFloatBox', {model: true, type: 'float-box-alert', content: content});
    return dispatch('showFloatBox')
  },
  confirm({dispatch}, content){
    dispatch('setFloatBox', {model: true, type: 'float-box-confirm', content: content});
    return dispatch('showFloatBox')
  },
  setFloatBox({commit}, config){
    commit(types.SET_FLOAT_BOX_CONFIG, config);
  },
  showFloatBox({commit}){
    return new Promise((resolve, reject)=> {
      commit(types.SET_FLOAT_BOX_PROMISE, {resolve, reject});

      commit(types.SHOW_FLOAT_BOX);
    })
  },
  hideFloatBox({commit}){
    commit(types.HIDE_FLOAT_BOX);
  },
  responseFloatBoxPromise({dispatch, state}, result = {success: true, data: null}){
    dispatch('hideFloatBox');
    if (result.success) {
      state.promise.resolve(result.data)
    }
    else {
      state.promise.reject(result.data)
    }
  }
};

export default {
  state,
  mutations,
  actions
};
